﻿using Common.Utils;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace WallpaperApi.Filter
{
    public class ModelValidationFilter : IActionFilter
    {
        /// <summary>
        /// 过滤数据注解特性
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var errors = context.ModelState.Values
                    .SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage);
                var errorMessage = string.Join("; ", errors);

                // 返回统一的错误响应
                context.Result = new BadRequestObjectResult(new ApiResponse<bool>
                {
                    IsSuccess = false,
                    Message = errorMessage,
                    Data = false,
                    Code = 400
                });
            }
        }

        public void OnActionExecuted(ActionExecutedContext context) { }
    }
}
